package models

import (
	"comment/util"
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego/orm"
)

type Badword struct {
	Id           int       `orm:"column(id);auto"`
	Name         string    `orm:"column(name);size(50)"`
	Status       int8      `orm:"column(status)"`
	Creator      int       `orm:"column(creator)"`
	CreateTime   time.Time `orm:"column(create_time);type(datetime)"`
	Modifier     int       `orm:"column(modifier);null"`
	ModifyTime   time.Time `orm:"column(modify_time);type(datetime);null"`
	ModifierName string    `orm:"-"`
	CreatorName  string    `orm:"-"`
}

func (t *Badword) TableName() string {
	return "badword"
}

func init() {
	orm.RegisterModel(new(Badword))
}

// AddBadword insert a new Badword into database and returns
// last inserted Id on success.
func AddBadword(m *Badword) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetBadwordById retrieves Badword by Id. Returns error if
// Id doesn't exist
func GetBadwordById(id int) (v *Badword, err error) {
	o := orm.NewOrm()
	v = &Badword{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllBadword retrieves all Badword matches certain condition. Returns empty list if
// no records exist
func GetAllBadword(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Badword))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Badword
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateBadword updates Badword by Id and returns error if
// the record to be updated doesn't exist
func UpdateBadwordById(m *Badword) (err error) {
	o := orm.NewOrm()
	v := Badword{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, "Name", "Status", "Modifier", "ModifyTime"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteBadword deletes Badword by Id and returns error if
// the record to be deleted doesn't exist
func DeleteBadword(id int) (err error) {
	o := orm.NewOrm()
	v := Badword{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Badword{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func PageBadwords(pageNo int, size int, query map[string]string, ck interface{}) util.Page {
	o := orm.NewOrm()
	var badword Badword
	var list []Badword
	qs := o.QueryTable(badword)
	for k, v := range query {

		if k == "creatorname" {
			qs = qs.Filter("Creator__in", FindLikeUserByName(query["creatorname"]))
		}
		if k == "modifier" {
			qs = qs.Filter("Modifier__in", FindLikeUserByName(query["modifier"]))
		}
		if k != "creatorname" && k != "modifier" {
			qs = qs.Filter(k, v)
		}
	}
	if ck != nil {
		qs = qs.Filter("Name__in", ck)
	}
	count, _ := qs.Limit(-1).Count()
	qs.Limit(size).Offset((pageNo-1)*size).All(&list, "Id", "Name", "Status", "Creator", "CreateTime", "Modifier", "ModifyTime")
	for j := 0; j < len(list); j++ {
		o.Raw("select name from user where id = ?", list[j].Creator).QueryRow(&list[j].CreatorName)
		o.Raw("select name from user where id = ?", list[j].Modifier).QueryRow(&list[j].ModifierName)
	}
	c, _ := strconv.Atoi(strconv.FormatInt(count, 10))
	//	orm.Debug = true
	return util.PageUtil(c, pageNo, size, list)
}

//根据敏感词查找用户
func GetUserIdByName(name string) (ids []string, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable("user")
	if _, err = qs.Filter("name__icontains", name).All(&ids, "Id"); err == nil {
		return ids, nil
	}
	return nil, err
}

//根据id修改启用状态
func UpdateStatusById(m *Badword) (err error) {
	o := orm.NewOrm()
	v := Badword{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, "Status", "Modifier", "ModifyTime"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func GetNameCount(name string) (count int64) {
	o := orm.NewOrm()
	var badword Badword
	qs := o.QueryTable(badword).Filter("name", name)
	count, _ = qs.Limit(-1).Count()
	return count
}
